import React, { useRef, useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Button, Space, notification } from 'antd';
import EditTree from '@/components/EditTree';
import { createMenu, queryMenu } from '@/services/menu';
import { mapData } from '@/utils/utils';

import type { EditTreeType } from '@/components/EditTree/data';
import type { MenuProps } from './src/data';
import styles from './index.module.less';

export interface IEidtTreeRef {
  current: any;
}

const MenuManager: React.FC<MenuProps> = () => {
  const [treeData, setTreeData] = useState<EditTreeType[]>([]);
  const [expandedKeyArr, setExpandedKeyArr] = useState<string[]>([]);

  const eidtTreeRef = useRef(null);

  const reducerExpendKey = (data: EditTreeType[], tempArr: string[]) => {
    data?.forEach((item: EditTreeType) => {
      tempArr.push(item.key as string);
      if (item.children) {
        reducerExpendKey(item.children, tempArr);
      }
    });
  };

  useEffect(() => {
    const getTreeData = async () => {
      const res = await queryMenu();
      if (res) {
        setTreeData(res.data?.menuData);
        // 默认菜单全部展开
        const keyArr: string[] = [];
        reducerExpendKey(res.data?.menuData, keyArr);
        setExpandedKeyArr(keyArr);
      }
    };
    getTreeData();
  }, []);

  // 父子通信
  const getTreeDate = async (data: EditTreeType[]) => {
    const menuData = mapData(data);
    const res = await createMenu({ menuData });
    if (res) {
      setTreeData(res.data.menuData);
      notification.success({
        message: res.message,
      });
      setTimeout(() => {
        window.location.reload();
      }, 500);
    }
  };

  const onSubmit = () => {
    const { current } = eidtTreeRef as IEidtTreeRef;
    if (current) {
      current.onSubmit();
    }
  };

  return (
    <PageContainer className={styles.menu_manager}>
      <Card>
        <Space direction="vertical">
          <EditTree
            canEditMenu
            expandedKeyArr={expandedKeyArr}
            editTreeData={treeData}
            getTreeDate={getTreeDate}
            ref={eidtTreeRef}
          />
          <Button type="primary" onClick={onSubmit}>
            提交
          </Button>
        </Space>
      </Card>
    </PageContainer>
  );
};

export default MenuManager;
